const express = require('express')
const router = express.Router()

const {User,Benner,Vegetable} = require('../mongodb')
const {sign,verify} = require('../util/jwt')
const {jwtSecret,IP,port} = require('../config')
const auth = require('../middleware/auth')
const vegetableAddress = `http://${IP}:${port}/vegetable`
const bannerAddress = `http://${IP}:${port}/banner`

//给客户端发送验证码
router.get('/getVerificationCode/:phone',async (req,res,next)=>{
    try{
        // 6位数随机数 string
        const code = Math.random().toFixed(6).slice(-6)
        //查找是否已有此账户，没有就创建 有就更新验证码
        const result = await User.findOne({phone:req.params.phone})
        if(result){
            const updata = await User.updateOne({phone:req.params.phone},{verificationCode:code})
        }else{
            const create = await User.create({
                phone:req.params.phone,
                verificationCode:code
            })
        }
        res.status(200).send(code)
    }catch(error){
        next(error)
    }
})

//接受 phone 和 code
//查找 phone 来对比 code 和 verificationCode 是否相等
router.get('/login',async (req,res,next)=>{
    try{
        const result = await User.findOne({phone:req.query.phone})
        if(result.verificationCode === req.query.code){
            const token = await sign({
                userId:result._id
            },jwtSecret)
            req.session.user = result
            console.log(result);
            res.json({
                flag:true,
                token
            })
        }else{
            res.json({
                flag:false
            })
        }
    }catch(error){
        next(error)
    }
})

router.get('/getBanner',async (req,res,next)=>{
    try{
        let result = await Benner.find()
        result.forEach(item=>{
            item.picture = bannerAddress + item.picture
        })
        res.send(result)
    }catch(error){
        next(error)
    }
})

const ver = [
    {
        name:'白菜',
        address:'/白菜.jpeg',
        price:4.99,
        beforePrice:12.99,
        classification:['特价','蔬菜'],
        sold:87,
        monthlySale:20,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'彩椒',
        address:'/彩椒.jpeg',
        price:15.99,
        beforePrice:21.99,
        classification:['特价','蔬菜'],
        sold:114,
        monthlySale:63,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'草莓',
        address:'/草莓.jpeg',
        price:51.99,
        beforePrice:55.99,
        classification:['特价','水果'],
        sold:193,
        monthlySale:57,
        memberDiscount:10,
        soldOut:true
    },
    {
        name:'大葱',
        address:'/大葱.jpeg',
        price:5.2,
        beforePrice:10.99,
        classification:['特价','蔬菜'],
        sold:205,
        monthlySale:37,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'蛋糕',
        address:'/蛋糕.jpeg',
        price:15.49,
        beforePrice:19.9,
        classification:['特价','休闲零食'],
        sold:99,
        monthlySale:98,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'豆角',
        address:'/豆角.jpeg',
        price:6.99,
        classification:['人气','蔬菜'],
        sold:73,
        monthlySale:17,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'红萝卜',
        address:'/红萝卜.jpeg',
        price:8.1,
        classification:['人气','蔬菜'],
        sold:107,
        monthlySale:40,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'胡萝卜',
        address:'/胡萝卜.jpeg',
        price:15.3,
        classification:['喜欢','蔬菜'],
        sold:21,
        monthlySale:7,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'黄瓜',
        address:'/黄瓜.jpeg',
        price:3.2,
        classification:['喜欢','蔬菜'],
        sold:53,
        monthlySale:21,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'鸡腿',
        address:'/鸡腿.jpeg',
        price:25.3,
        classification:['人气','喜欢','肉类'],
        sold:27,
        monthlySale:20,
        memberDiscount:9,
        soldOut:false
    },
    {
        name:'尖椒',
        address:'/尖椒.jpeg',
        price:12.3,
        classification:['人气','喜欢','蔬菜'],
        sold:81,
        monthlySale:53,
        memberDiscount:8.8,
        soldOut:false
    },
    {
        name:'面包',
        address:'/面包.jpeg',
        price:3.5,
        classification:['喜欢','休闲零食'],
        sold:192,
        monthlySale:43,
        memberDiscount:7.1,
        soldOut:false
    },
    {
        name:'蘑菇',
        address:'/蘑菇.jpeg',
        price:22.3,
        classification:['人气','蔬菜'],
        sold:87,
        monthlySale:12,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'南瓜',
        address:'/南瓜.jpeg',
        price:15.3,
        classification:['人气','蔬菜'],
        sold:31,
        monthlySale:11,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'牛排',
        address:'/牛排.jpeg',
        price:35.3,
        classification:['人气','喜欢','肉类'],
        sold:87,
        monthlySale:20,
        memberDiscount:10,
        soldOut:true
    },
    {
        name:'胖辣椒',
        address:'/胖辣椒.jpeg',
        price:18.43,
        classification:['人气','蔬菜'],
        sold:56,
        monthlySale:12,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'芹菜',
        address:'/芹菜.jpeg',
        price:9.99,
        classification:['人气','蔬菜'],
        sold:43,
        monthlySale:17,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'秋葵',
        address:'/秋葵.jpeg',
        price:21.3,
        classification:['人气','蔬菜'],
        sold:87,
        monthlySale:20,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'酸黄瓜',
        address:'/酸黄瓜.jpeg',
        price:7.62,
        classification:['人气','蔬菜'],
        sold:87,
        monthlySale:54,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'五花肉',
        address:'/五花肉.jpeg',
        price:6.31,
        classification:['人气','喜欢','肉类'],
        sold:87,
        monthlySale:29,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'西瓜',
        address:'/西瓜.jpeg',
        price:2.12,
        classification:['人气','喜欢','水果'],
        sold:93,
        monthlySale:32,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'西红柿',
        address:'/西红柿.jpeg',
        price:3.99,
        classification:['人气','蔬菜'],
        sold:72,
        monthlySale:40,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'西兰花',
        address:'/西兰花.jpeg',
        price:15.3,
        classification:['人气','蔬菜'],
        sold:54,
        monthlySale:26,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'虾尾',
        address:'/虾尾.jpeg',
        price:35.56,
        classification:['人气','喜欢','海鲜水产'],
        sold:53,
        monthlySale:15,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'小青菜',
        address:'/小青菜.jpeg',
        price:12.1,
        classification:['人气','蔬菜'],
        sold:264,
        monthlySale:65,
        memberDiscount:10,
        soldOut:false
    },
    {
        name:'玉米',
        address:'/玉米.jpeg',
        price:35.56,
        classification:['人气','蔬菜'],
        sold:34,
        monthlySale:9,
        memberDiscount:10,
        soldOut:false
    },
]
router.get('/pushvegetable', async (req,res)=>{
    const result = await Vegetable.deleteMany({})
    let arr = [];
    for(let item of ver){
        arr.push(Vegetable.create(item))
    }
    Promise.all(arr).then(re=>{
        res.send(re)
    })
})

//手动添加用户信息
router.get('/pushuser',async (req,res)=>{
    const result = await User.create({
        name:'华敬彬',
        phone:'18969786414',
        account:'hua',
        password:'hjb19991115',
        shoppingCart:['61970c195321ac8b0cc51300','61970c195321ac8b0cc5130b','61970c195321ac8b0cc51307'],
        address:'河南省郑州市金水区须水街道',
        headPortrait:'http://localhost:4399/headPortrait/touxiang.jpeg'

    })
    res.send(result)
})

//

router.get('/vegetableClassification',async (req,res,next)=>{
    try{
         const type = req.query.type
         const limit = parseInt(req.query.limit)
        let result = await Vegetable.find({classification:{$in:[type]}}).limit(limit).select('-classification')
        // let result = await Vegetable.find()

        //修改 vegetable 的地址为当前 ip 加 路径 文件名
        result = result.map(item=>{
            item.address = vegetableAddress + item.address
            return item
        })
        res.send(result)
    }catch(error){
        next(error)
    }
})

router.get('/shoppingCart',async (req,res,next)=>{
    try{
        // console.log(req.session.user._id);
        let result = await User.findById(req.session.user._id).populate('shoppingCart').select('shoppingCart')
        result.shoppingCart.forEach(item=>{
            item.address = vegetableAddress + item.address
        })
        res.send(result)
    }catch(error){
        next(error)
    }
})

//TODO:改成 使用 session 获取用户信息 jwt 进行验证
router.get('/user_information',auth, async (req,res,next)=>{
    try{
        // const token = req.headers.token
        // const user = await verify(token,jwtSecret)
        const result = await User.findById(req.session.user._id).select('-_id -shoppingCart -password -verificationCode')
        delete result.password
        res.send(result)
    }catch(error){
        next(error)
    }
})

//接收两个 query 值
//userId：用户 id
//vegetableId：加入购物车的 蔬菜 id
//TODO:加入 jwt 验证
router.put('/addshoppingcart/:vegetableId',auth,async (req,res,next)=>{
    try{
        !req.session.user.shoppingCart.some(item=>item === req.params.vegetableId) ?
            req.session.user.shoppingCart.push(req.params.vegetableId)
        :
            res.send('已存在')

        const result = await User.updateOne({_id:req.session.user._id},{shoppingCart:req.session.user.shoppingCart})
        result.shoppingCartLength =  req.session.user.shoppingCart.length
        res.send(result)
    }catch(error){
        next(error)
    }
})

// NOTE:关联类型的值无法直接进行比对，可以对 session 进行操作然后进行赋值

//删除购物车内容
router.get('/delshoppingcart/:vegetableId',auth,async (req,res,next)=>{
    try{
        const shoppingCart = req.session.user.shoppingCart
        req.session.user.shoppingCart = shoppingCart.filter(item=>item !== req.params.vegetableId)
        const result = await User.updateOne({_id:req.session.user._id},{shoppingCart:req.session.user.shoppingCart})
        result.shoppingCartLength =  req.session.user.shoppingCart.length
        res.send(result)
    }catch(error){
        next(error)
    }
})

router.post('/realname',auth,async (req,res,next)=>{
    try{
        const result = await User.updateOne({_id:req.session.user._id},{ID:req.body.ID,hometown:req.body.hometown,house:req.body.house})
        if(result.acknowledged){
            const message = await User.updateOne({_id:req.session.user._id},{realName:true})
            res.send(message)
        }else{
            res.status(400).send(result)
        }

    }catch(error){
        next(error)
    }
})




module.exports = router